// MIT License (MIT)
// 
// Copyright (c) 2014 K Ercan Turkarslan
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
// 

using System;
using System.Net.Http;
using Mios.MiosConnection.JSONStructures;

namespace Mios.MiosConnection
{
    public sealed class Ui7Controller : MiosController
    {
        public DateTime LastAliveReported { get; private set; }
        public String MacAddress { get; private set; }
        public Int32 Account { get; private set; }
        public Int32 DeviceSubType { get; private set; }
        public Int32 DeviceType { get; private set; }
        public String AccountServer { get; private set; }
        public String DeviceServer { get; private set; }
        public String EventServer { get; private set; }

        public JsonUi7ControllerDetail ControllerDetail { get; private set; }

        public JsonIdentityPackage AuthenticationIdentity { get; private set; }

        #region Constructor(s)

        internal Ui7Controller(String username, JsonUi7Controller controller, JsonIdentityPackage authenticationIdentity)
            : base(controller.PkDevice.ToString(), controller.LocalIpAddress, username, null)
        {
            LastAliveReported = DateTime.Parse(controller.LastAliveReported);
            MacAddress = controller.MacAddress;
            Account = controller.PkAccount;
            DeviceSubType = controller.PkDeviceSubType;
            DeviceType = controller.PkDeviceType;
            AccountServer = controller.ServerAccount;
            DeviceServer = controller.ServerDevice;
            EventServer = controller.ServerEvent;

            AuthenticationIdentity = authenticationIdentity;
        }

        #endregion

        internal void GetDeviceDetail(String deviceServer)
        {
            var deviceStream = HttpConnection.HttpGetStream(
                String.Format("https://{0}/device/device/device/{1}", deviceServer, Int32.Parse(EngineSerial)),
                AuthenticationIdentity.IdentityBase64,
                AuthenticationIdentity.IdentitySignature);

            ControllerDetail =
                SimpleJsonSerializer.Deserialize(typeof (JsonUi7ControllerDetail), deviceStream) as JsonUi7ControllerDetail;
        }

        #region Connection overrides

        public override Boolean IsConnectionStale()
        {
            if (AuthenticationIdentity.IsStale && IsConnected())
                CloseConnection();

            return AuthenticationIdentity.IsStale;
        }

        public override Boolean EstablishLocalConnection()
        {
            Connection = !base.EstablishLocalConnection() ? null :
                new HttpClient
                {
                    Timeout = TimeSpan.FromMinutes(2),
                    BaseAddress = new Uri(String.Format("http://{0}/port_3480/", LocalIpAddress))
                };

            return (Connection != null);
        }

        public override Boolean EstablishRemoteConnection(Boolean useSecondaryServer = false)
        {
            if (IsConnected())
                CloseConnection();

            if (AuthenticationIdentity.IsStale)
                return false;

            Connection = new HttpClient
                {
                    Timeout = TimeSpan.FromMinutes(2),
                    BaseAddress = new Uri(String.Format("https://{0}/relay/relay/relay/device/{1}/port_3480/", ControllerDetail.RelayServer, ControllerDetail.PkDevice))
                };

            Connection.DefaultRequestHeaders.Add("MMSAuth", AuthenticationIdentity.IdentityBase64);
            Connection.DefaultRequestHeaders.Add("MMSAuthSig", AuthenticationIdentity.IdentitySignature);

            return true;
        }

        #endregion
    }
}